from django.db import transaction
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import permissions
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from .models import Upload, Option, SystemLog
from .serializers import OptionSerializer, UploadSerializer
from .filters import OptionFilter


class OptionViewSet(CustomModelViewSet):
    permission_classes = [permissions.IsAdminUser]
    queryset = Option.objects.filter()
    serializer_class = OptionSerializer

    def filter_queryset(self, queryset):
        print(self.request.GET)
        f = OptionFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    @action(methods=['get'], detail=False)
    def dict_data(self, request):
        '''获取所有类型的字典'''
        ret = {
            'option_type': Option.TYPE_JSON,
        }
        return response_ok(ret)


class UploadEditorImageView(APIView):

    def post(self, request):
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                instance = Upload.objects.upload(file, 'editor')
                return Response({
                    "errno": 0,
                    "data": [
                        instance.get_url()
                    ]
                })
        except Exception as e:
            return Response({
                "errno": 1
            })


class UploadView(APIView):
    permission_classes = [permissions.IsAdminUser]

    def post(self, request):
        save_path = self.request.GET.get('savePath', 'editor')
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                instance = Upload.objects.upload(file, save_path)
                ser = UploadSerializer(instance)
                SystemLog.objects.add_log(request.user, SystemLog.INSERT, '上传图片', ser.data)
                return response_ok(ser.data)
        except Exception as e:
            return response_error(str(e))


class MenuView(APIView):
    def get(self, request):
        menu = [
            {
                'name': '用户管理',
                'path': '/user',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '管理员列表',
                        'path': '/user',
                    },
                    {
                        'name': '会员列表',
                        'path': '/member',
                    }
                ]
            },
            {
                'name': '文章管理',
                'path': '/article',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '文章列表',
                        'path': '/article',
                    },
                    {
                        'name': '装修百科',
                        'path': '/adorn_pedia',
                    },
                    {
                        'name': '装修流程',
                        'path': '/adorn_process',
                    }
                ]
            },
            {
                'name': '工人管理',
                'path': '/worker',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '工人列表',
                        'path': '/worker',
                    }
                ]
            },
            {
                'name': '产品管理',
                'path': '/product',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '产品列表',
                        'path': '/product',
                    }
                ]
            },
            {
                'name': '服务管理',
                'path': '/service',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '服务列表',
                        'path': '/service',
                    }
                ]
            },
            {
                'name': '案例管理',
                'path': '/house',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '案例列表',
                        'path': '/house',
                    }
                ]
            },
            {
                'name': '系统管理',
                'path': '/system',
                'icon': 'iconfont icon-chuangzuo1',
                'children': [
                    {
                        'name': '系统分类',
                        'path': '/option',
                    },
                    {
                        'name': '优惠卷',
                        'path': '/coupons',
                    }

                ]
            }
        ]
        return response_ok(menu)


class CreateCeleryTask(APIView):
    def get(self, request):
        from .tasks import tasks_add
        # result = tasks_add.delay(4, 4)
        # 定时任务
        import datetime
        ctime = datetime.datetime.now()
        utc_time = datetime.datetime.utcfromtimestamp(ctime.timestamp())
        target_time = utc_time + datetime.timedelta(seconds=10)
        result = tasks_add.apply_async(args=[11, 3], eta=target_time)

        return response_ok(result.id)


class GetCeleryTask(APIView):
    def get(self, request):
        task_id = request.data['task_id']
        from celery.result import AsyncResult
        from qiaofinn_adorn import celery_app
        result = AsyncResult(id=task_id, app=celery_app)
        if result.successful():
            result = result.get()
            return response_ok(result)
            # result.forget() # 将结果删除
        return response_ok('失败')
